local addonName = "PSLibBar";
local moduleName = "Panels";
local Addon = LibStub("AceAddon-3.0"):GetAddon(addonName);
local Module = Addon:NewModule(moduleName);

local L = LibStub("AceLocale-3.0"):GetLocale(addonName);
local AceGUI = LibStub("AceGUI-3.0")

Module.defaults =
{
	
}

Module.optionTable = 
{
	order = 1.1,
	name = L["Panels.Settings.Title"],
	type = "group",
	handler = Module, get = "GetValue", set = "SetValue",
	childGroups ="tree",
	args = 
	{ 
		["Panels.Settings.AddPanel"] =
		{ 
			order = 1,
			name = L["Panels.Settings.AddPanel"], 
			type = "execute",
			func = "AddPanel",
		},
		["Panels.Settings.RemovePanel"] =
		{ 
			order = 1.1,
			name = L["Panels.Settings.RemovePanel"], 
			type = "execute",
			func = "RemovePanel",
		},
	}
}
Module.activePanels = {};
function Module:OnInitialize()
	
end

function Module:OnEnable()
	
end

function Module:OnSettingsChanged()
	Module:UpdatePanels();
end

function Module:AddPanel()
	for iterator = 0, 100 do
		if(not self.db["Panel " .. iterator]) then
			self.db["Panel " .. iterator] = Module:GetPanelTemplateDefaults();
			break;
		end
	end
	
	Addon:UpdateSettings();
end

function Module:RemovePanel()
	local status = LibStub("AceConfigDialog-3.0"):GetStatusTable(addonName, {moduleName} )	
	if(self.db[status.groups.selected]) then
		self.db[status.groups.selected] = nil;
	end

	Addon:UpdateSettings();
end

function Module:UpdatePanels()
	for name, panel in pairs(Module.activePanels) do
		if(self.db[name]) then
			panel:ApplySettings(self.db[name]);
		else
			-- Remove panel
			panel:Dispose();
			Module.activePanels[name] = nil;
			Module.optionTable.args[name] = nil;
		end
	end
	
	for name, panelSettings in pairs(self.db) do
		if(not Module.activePanels[name]) then
			local newPanel = Module:CreatePanel();
			newPanel:ApplySettings(panelSettings);
			
			Module.activePanels[name] = newPanel;
			Module.optionTable.args[name] = newPanel.optionTable;
		end
	end
end
